import { defineStore } from 'pinia'
import api from '/src/utils/request/BaseRequest'
import { ElMessage } from 'element-plus'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { encrypt } from '@/utils/rsaEncrypt'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    username: '',
    imgHeader: '',
    sex: '',
    ifTourist: '',
    userId: '',
    userDetail: {},
  }),

  getters: {
    sex: (state) => state.sex,
    username: (state) => state.username,
    resourceMain: () => ({
      staticWebsite: process.env.VUE_APP_BASE_API || ''
    }),
  },

  actions: {
    setUserId(data) {
      this.userId = data
    },
    setToken(token) {
      this.token = token
    },
    setUsername(username) {
      this.username = username
    },
    setImgHeader(imgHeader) {
      this.imgHeader = imgHeader
    },
    setUserDetail(userDetail) {
      this.userDetail = userDetail
    },
    setSex(data) {
      this.sex = data
    },
    setIfTourist(data) {
      this.ifTourist = data
    },

    // 登录
    async login(userInfo) {
      const userName = userInfo.userName.trim()
      const password = encrypt(userInfo.password)
      const captcha = userInfo.captcha
      
      try {
        const res = await api.post('/module/user/userinfo/login', { 
          userName, password, captcha 
        })
        
        if (res.status) {
          setToken(res.data)
          this.setToken(res.data)
          ElMessage({message: '登录成功，欢迎来到创意宝！', type: 'success'})
          // TODO: 需要迁移 CLEAR_DIALOG action
          setTimeout(() => {
            window.location.href = "/"
          }, 500)
        } else {
          ElMessage({message: res.message, type: 'error'})
        }
      } catch (error) {
        console.error(error)
        ElMessage({message: '登录失败', type: 'error'})
      }
    },

    // 游客登录
    async touristLogin() {
      try {
        const res = await api.get('/module/user/userinfo/touristLogin')
        if (res.status) {
          setToken(res.data)
          this.setToken(res.data)
          ElMessage({message: '登录成功，欢迎来到创意宝！', type: 'success'})
          // TODO: 需要迁移 CLEAR_DIALOG action
          setTimeout(() => {
            window.location.href = "/"
          }, 500)
        } else {
          ElMessage({message: res.message, type: 'error'})
        }
      } catch (error) {
        console.error(error)
        ElMessage({message: '游客登录失败', type: 'error'})
      }
    },

    // 退出系统
    async logout() {
      try {
        const res = await api.post('/auth/system/logout')
        if (res.status) {
          this.setToken('')
          removeToken()
          ElMessage({message: '退出成功', type: 'success'})
          setTimeout(() => window.location.href = "/", 500)
        } else {
          ElMessage({message: res.message, type: 'error'})
        }
      } catch (error) {
        console.error(error)
        ElMessage({message: '退出失败', type: 'error'})
      }
    },

    // 获取用户信息
    async getInfo() {
      try {
        const res = await api.get('/module/user/userinfo/getInfo')
        if (res.status) {
          const data = res.data
          this.setUserDetail(data)
          this.setUsername(data.userName || data.ipaddress)
          this.setUserId(data.id)
          this.setImgHeader(data.imgUrl)
          this.setSex(data.sex)
          this.setIfTourist(data.ifTourist)
          // TODO: 需要迁移 SET_LOADING_STATE_USER_INFO action
        } else {
          ElMessage({message: res.message, type: 'error'})
        }
        return res
      } catch (error) {
        console.error(error)
        ElMessage({message: '获取用户信息失败', type: 'error'})
        throw error
      }
    }
  }
})
